package com.workable.assignment.logging;

import java.util.List;

import javax.ws.rs.core.Response;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.workable.assignment.services.ws.responses.MovieRamaResponse;
import com.workable.assignment.utilities.StringUtil;

/**
 * 
 * The class MovieRamaLoggingManager implements logging mechanism
 * 
 * @author npapadopoulos
 * @date Oct 23, 2014
 * 
 */
@Aspect
@Component
public class MovieRamaLoggingManager {

	private static final Logger LOG = (Logger) LoggerFactory.getLogger(MovieRamaLoggingManager.class);

	@Before("execution(@com.workable.assignment.annotations.Loggable * *(..))")
	public void logBefore(JoinPoint jp) {
		LOG.info("{}: {}", jp.getSignature().toShortString(), StringUtil.toString(jp.getArgs()));
	}

	@AfterReturning(pointcut = "execution(* com.workable.assignment.services.api.MovieRamaApiService.*(..))", returning = "response")
	public void logAfterApiCall(JoinPoint jp, Object response) throws Throwable {
		if (response instanceof List<?> && response != null) {
			List<?> result = (List<?>) response;
			LOG.info("{} {} movie(s) found.", jp.getSignature().toShortString(), StringUtil.toString(result.size()));
		}
	}

	@AfterReturning(pointcut = "execution(* com.workable.assignment.services.ws.MovieRamaService.*(..))", returning = "response")
	public void logAfterWSCall(JoinPoint jp, Object response) throws Throwable {
		if (response instanceof Response && response != null) {
			Response result = (Response) response;
			LOG.info("{} Total {} movie(s) found.", jp.getSignature().toShortString(), StringUtil.toString(((MovieRamaResponse) result.getEntity()).getMovies().size()));
		}
	}
}
